﻿using HCQ2_Common;
using HCQ2_Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using HCQ2_Model.ViewModel;
using HCQ2_Model.VRDevice.ParamModel;
using HCQ2_Model.VRDevice.ResultModel;
using System.Web;
using System.IO;
using System.Diagnostics;

namespace HCQ2UI_Logic.DocumentController
{
    /// <summary>
    ///  VR设备管理
    /// </summary>
    public class VRDeviceController : BaseLogic
    {
        //**************************1.0 VR设备*****************************
        #region 1.0 初始化Table + ActionResult InitTable()
        /// <summary>
        ///  初始化Table
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InitTable(VRdeviceParam model)
        {
            if (model.folder_id == 0)
                return null;
            int total = 0;
            model.user_id = operateContext.Usr.user_id;
            List<VRdeviceResult> list = operateContext.bllSession.T_DocumentInfo.GetVRDeviceList(model,out total);
            TableModel tModel = new TableModel()
            {
                total = total,
                rows = list
            };
            return Json(tModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 1.1 添加设备 + ActionResult AddDevice(DeviceParam param)
        /// <summary>
        ///  添加设备
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddDevice(DeviceParam param)
        {
            ModelState.Remove("file_id");
            if (!ModelState.IsValid)
                return operateContext.RedirectAjax(1, getErrorMessage(ModelState), "", "");
            //添加之前判断code是否已被占用
            int mark = operateContext.bllSession.T_DocumentInfo.SelectCount(s => s.file_code.Equals(param.file_code) && s.file_status==5 && !s.if_remove);
            if(mark>0)
                return operateContext.RedirectAjax(1, "设备代码已存在，请重新输入！", "", "");
            //添加设备
            T_DocumentInfo file = new T_DocumentInfo
            {
                file_name = param.file_name,
                file_code = param.file_code,
                file_note = param.file_note,
                file_order = param.file_order,
                qr_code = param.qr_code,
                file_status = 5,
                file_classify = "",
                doc_type = "",
                folder_num = "",
                page_type = "VRDevice",
                create_time = DateTime.Now,
                create_id = operateContext.Usr.user_id,
                create_name = operateContext.Usr.user_name,
                update_name = operateContext.Usr.user_name,
                update_time = DateTime.Now
            };
            mark = operateContext.bllSession.T_DocumentInfo.Add(file);
            if(mark<=0)
                return operateContext.RedirectAjax(1, "添加失败！", "", "");
            //添加：设备导航树关系
            T_DocumentFolderRelation relation = new T_DocumentFolderRelation
            {
                file_id = file.file_id,
                folder_id = param._folder_id,
                folder_path = param._folder_path,
                create_id = operateContext.Usr.user_id
            };
            operateContext.bllSession.T_DocumentFolderRelation.Add(relation);
            //添加：价格明细
            param.price?.ForEach(o => {
                T_VRGoodDisiPrice disPrice = new T_VRGoodDisiPrice
                {
                    op_code = Helper.GetGuid,
                    file_code = param.file_code,
                    file_id = file.file_id,
                    op_month = o.op_month,
                    ori_price = o.ori_price,
                    price_name = o.price_name,
                    price_type = 1
                };
                operateContext.bllSession.T_VRGoodDisiPrice.Add(disPrice);
            });            
            return operateContext.RedirectAjax(0, "添加设备成功~", "", "");
        }
        #endregion

        #region 1.2 编辑设备 + ActionResult EditDevice(DeviceParam param)
        /// <summary>
        ///  添加设备
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditDevice(DeviceParam param)
        {
            if(param.file_id<=0)
                return operateContext.RedirectAjax(1,"设备id异常！", "", "");
            if (!ModelState.IsValid)
                return operateContext.RedirectAjax(1, getErrorMessage(ModelState), "", "");
            //添加设备
            T_DocumentInfo file = new T_DocumentInfo
            {
                file_name = param.file_name,
                file_code = param.file_code,
                file_note = param.file_note,
                file_order = param.file_order,
                qr_code = param.qr_code,
                update_name=operateContext.Usr.user_name,
                update_time=DateTime.Now,
            };
            //判断修改的code是否被占用
            int mark = operateContext.bllSession.T_DocumentInfo.SelectCount(s => s.file_code.Equals(param.file_code) && s.file_id!=param.file_id && s.file_status == 5 && !s.if_remove);
            if (mark > 0)
                return operateContext.RedirectAjax(1, "修改的设备代码已存在，请重新输入！", "", "");
            operateContext.bllSession.T_DocumentInfo.Modify(file,s=>s.file_id==param.file_id, "file_name", "file_code", "file_note", "file_order", "qr_code", "update_name", "update_time");
            //修改：设备导航树关系
            T_DocumentFolderRelation relation = new T_DocumentFolderRelation
            {
                folder_id = param._folder_id,
                folder_path = param._folder_path
            };
            operateContext.bllSession.T_DocumentFolderRelation.Modify(relation, s => s.file_id == param.file_id, "folder_id", "folder_path");
            //修改：价格明细
            operateContext.bllSession.T_VRGoodDisiPrice.Delete(s => s.file_id == param.file_id);
            param.price?.ForEach(o => {
                T_VRGoodDisiPrice disPrice = new T_VRGoodDisiPrice
                {
                    op_code = Helper.GetGuid,
                    file_code = param.file_code,
                    file_id = param.file_id,
                    op_month = o.op_month,
                    ori_price = o.ori_price,
                    price_name = o.price_name,
                    price_type = 1
                };
                operateContext.bllSession.T_VRGoodDisiPrice.Add(disPrice);
            });
            return operateContext.RedirectAjax(0, "修改设备成功~", "", "");
        }
        #endregion

        #region 1.3 获取设备价格列表 + ActionResult GetPriceList(int id)
        /// <summary>
        ///  获取设备价格列表
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetPriceList(int id)
        {
            VRdeviceResult obj = operateContext.bllSession.T_DocumentInfo.GetVRDevicePrice(id);
            List<T_VRGoodDisiPrice> list = operateContext.bllSession.T_VRGoodDisiPrice.Select(s => s.file_id == id).OrderBy(s => s.op_month).ToList();
            ResltDevice result = new ResltDevice
            {
                file_id = obj.file_id,
                file_code = obj.file_code,
                file_name = obj.file_name,
                _folder_name = obj.folder_name,
                _folder_id = obj.folder_id,
                _folder_path = obj.folder_path,
                file_note = obj.file_note,
                file_order = obj.file_order,
                qr_code = obj.qr_code,
                create_time = obj.create_time,
                create_name = obj.create_name,
                update_time = obj.update_time,
                update_name = obj.update_name
            };
            List<PriceParam> price = new List<PriceParam>();
            list.ForEach(s => price.Add(new PriceParam { price_name = s.price_name, op_month = s.op_month, ori_price = s.ori_price }));
            result.price = price;
            return operateContext.RedirectAjax(0, "", result, "");
        }
        #endregion

        //**************************2.0 批量编辑*****************************
        #region 12 批量编辑 + ActionResult SaveBatchData()
        /// <summary>
        ///  批量编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveBatchData()
        {
            int folder_id = RequestHelper.GetIntByName("folder_id");//导航id
            string fileIds = RequestHelper.GetStrByName("fileIds"),//作品id集合
                folder_path = RequestHelper.GetStrByName("folder_path");//导航path
            if(string.IsNullOrEmpty(fileIds))
                return operateContext.RedirectAjax(1, "待修改的作品id为空！", "", "");
            if (folder_id<=0 || string.IsNullOrEmpty(folder_path))
                return operateContext.RedirectAjax(1, "导航目录id异常！", "", "");
            try
            {
                string[] fileID = fileIds.Split(',');
                T_DocumentFolderRelation folderRel = new T_DocumentFolderRelation { folder_id = folder_id, folder_path = folder_path };
                //编辑导航目录
                foreach (string item in fileID)
                {
                    int file_id = Helper.ToInt(item);
                    operateContext.bllSession.T_DocumentFolderRelation.Modify(folderRel, s => s.file_id == file_id, "folder_id", "folder_path");
                }
                return operateContext.RedirectAjax(0, "数据更新成功~", "", "");
            }
            catch(Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 2.1 批量导入：添加设备 + ActionResult ImportDevice(HttpPostedFileBase excelFile)
        /// <summary>
        ///  添加设备
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ImportDevice(HttpPostedFileBase excelFile)
        {
            try
            {
                if (excelFile == null)
                    return operateContext.RedirectAjax(1, "请选择导入文件！", "", "");
                if (!Path.GetExtension(excelFile.FileName).Equals(".xlsx"))
                    return operateContext.RedirectAjax(1, "导入文件限定为.xlsx格式的excel文件！", "", "");
                //新的文件名
                string batchCode = Helper.GetGuid;
                #region 导入文件到临时目录
                string path = Server.MapPath("~/UpFile/ImportDevice/temp/");
                if (!Directory.Exists(path.ToString()))
                    Directory.CreateDirectory(path.ToString());//文件夹不存在则创建
                string tempPath = Server.MapPath("~/UpFile/ImportDevice/temp/") + batchCode + ".xlsx";
                excelFile.SaveAs(tempPath);
                #endregion
                Stopwatch sw1 = new Stopwatch();
                sw1.Start();
                bool importDevice;
                List<string> mess = operateContext.bllSession.T_DocumentInfo.importDevice(tempPath, out importDevice);
                sw1.Stop();
                if (importDevice)
                    return operateContext.RedirectAjax(0, string.Format("导入成功 用时：{0}秒。", Math.Round((double)sw1.ElapsedMilliseconds / 1000, 2)), (mess.Count > 0 ? mess : null), "");
                //导入成功删除临时文件
                if (System.IO.File.Exists(tempPath))
                    System.IO.File.Delete(tempPath);
                return operateContext.RedirectAjax(1, "数据导入失败~", mess, "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion
    }
}
